package com.erp.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Properties;


/**
 * 类说明：以流的形式返回至浏览器
 *
 */
@Component
public class FtpOperationUtil{


    // ftp客户端
    private FTPClient ftpClient = new FTPClient();

    /**
     *
     * 功能：根据文件名称，下载文件流
     * @param filename 文件名
     * @return
     * @throws IOException
     */
    public void download(String filename, HttpServletResponse response, HttpServletRequest request) throws IOException {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        BufferedInputStream bis=null;
        String downloadRange = request.getHeader("Range");
        try {
            // 读取文件
            File downloadFile = new File(filename);
            int downloadFileSize = Integer.parseInt(String.valueOf(downloadFile.length()));
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-download");
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-Length", String.valueOf(downloadFileSize));
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + URLEncoder.encode(filename,"UTF-8"));
//            inputStream = zipUnit.zipOut(filename);
//            zipUnit.zipOut1(inputStream,"C:\\Users\\ceil\\Desktop\\tem\\test");
//            FileInputStream in=new FileInputStream(new File("C:\\Users\\ceil\\Desktop\\tem\\test"));
          inputStream = new FileInputStream(downloadFile);
            long pos = 0;
            if (StringUtils.isNotEmpty(downloadRange)) {
                try {
                    pos = Long.parseLong(downloadRange.replaceAll("bytes=", "")
                            .replaceAll("-", ""));
                } catch (NumberFormatException e) {
                    System.err.println("Number Format error!"+e);
                    pos = 0;
                }
            }
            if (downloadFileSize > pos) {
                if (pos > 0) {
                    // 断点续传
                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                }
                // 输出文件
                outputStream = response.getOutputStream();
                String contentRange = new StringBuffer("bytes ").append(pos + "")
                        .append("-").append((downloadFileSize - 1) + "").append("/")
                        .append(downloadFileSize + "").toString();
                response.setHeader("Content-Range", contentRange);
                inputStream.skip(pos);
                byte[] buffer = new byte[1024 * 10];
                int length = 0;
                while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
                    outputStream.write(buffer, 0, length);
                }
            }
//            bis = new BufferedInputStream(in);
//                OutputStream out = response.getOutputStream();
//                byte[] buf = new byte[1024];
//                int len = 0;
//                while ((len = bis.read(buf)) > 0) {
//                    out.write(buf, 0, len);
//                }
//                out.flush();
            //返回结果
        } catch (Exception e) {
            System.err.println("异常"+e);
        }  finally {
            // 释放资源
            try {
                if (null != outputStream) {
                    outputStream.flush();
                }
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
                if(bis!=null){
                    bis.close();
                }
            } catch (Exception e) {
                System.err.println("异常"+e);
            }
        }
//        Properties properties = PropertiesUtils.loadProperties("ftp");
//        String ip = properties.getProperty("ftpHost");
//        int port = Integer.parseInt(properties.getProperty("ftpPort"));
//        String userName = properties.getProperty("ftpUserName");
//        String passWord = properties.getProperty("ftpPassword");
//       String  LOCAL_CHARSET=properties.getProperty("LOCAL_CHARSET");
//       /* String ip="175.24.18.145";
//        int port=2121;
//        String userName="ftpprod";
//        String passWord="ftpprod";*/
//        // 获取ftp信息
//       /*String[] ftpStrs = fileDir.split(":");
//        if (ftpStrs.length > 0){
//            ip = ftpStrs[0];
//            port = Integer.parseInt(ftpStrs[1]);
//            userName = ftpStrs[2];
//            passWord = ftpStrs[3];
//        }*/
//        // 获取文件名称
//        String[] strs = filename.split("/");
//        String downloadFile = strs[strs.length - 1];
//        try {
//            // 设置文件ContentType类型，这样设置，会自动判断下载文件类型
//            response.setContentType("application/x-msdownload");
//            // 设置文件头：最后一个参数是设置下载的文件名并编码为UTF-8
//            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8"));
//            // 建立连接
//            connectToServer(ip,port,userName,passWord);
//            ftpClient.enterLocalPassiveMode();
//            // 设置传输二进制文件
//            int reply = ftpClient.getReplyCode();
//            String path= filename.substring(1,filename.lastIndexOf("/")+1).replace("\"","");
//            ftpClient.changeWorkingDirectory(path);
//            if(!FTPReply.isPositiveCompletion(reply)) {
//                ftpClient.disconnect();
//                throw new IOException("failed to connect to the FTP Server:"+ip);
//            }
//            // 此句代码适用Linux的FTP服务器
//            String newPath = new String(filename.getBytes(LOCAL_CHARSET),"ISO-8859-1");
//            // ftp文件获取文件
//            InputStream is = null;
//            BufferedInputStream bis = null;
//            try {
//                is = ftpClient.retrieveFileStream(newPath);
//                bis = new BufferedInputStream(is);
//                OutputStream out = response.getOutputStream();
//                byte[] buf = new byte[1024];
//                int len = 0;
//                while ((len = bis.read(buf)) > 0) {
//                    out.write(buf, 0, len);
//                }
//                out.flush();
//            } catch (Exception e) {
//                e.printStackTrace();
//            } finally {
//                closeConnect();
//                if (bis != null) {
//                    try {
//                        bis.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//                if (is != null) {
//                    try {
//                        is.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 连接到ftp服务器
     */
    private void connectToServer(String ip,int port,String userName,String passWord) throws Exception {
        if (!ftpClient.isConnected()) {
            int reply;
            try {
                ftpClient=new FTPClient();
                ftpClient.connect(ip,port);
                ftpClient.login(userName,passWord);
                reply = ftpClient.getReplyCode();

                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    // LOGGER.info("connectToServer FTP server refused connection.");
                }

            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }
    /**
     *
     * 功能：关闭连接
     */
    public void closeConnect() {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}